package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.entity.Product;
import cn.tedu.coolshark.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
public class ProductController {
    //找到配置文件中的值赋值给dirPath变量
    @Value("${dirPath}")
    private String dirPath;

    @Autowired(required = false)
    ProductMapper mapper;

    @RequestMapping("/product/insert")
    public void insert(@RequestBody Product product){
        System.out.println("product = " + product);
        product.setCreated(new Date());
        mapper.insert(product);
    }

    @RequestMapping("/product/select")
    public List<Product> select(){
        return mapper.select();
    }

    @RequestMapping("/product/delete")
    public void delete(int id){
        String url = mapper.selectById(id);
        new File(dirPath+"/"+url).delete();
        mapper.delete(id);
    }

    @RequestMapping("/product/select/index")
    public List<Product> selectIndex(){
        return mapper.selectIndex();
    }

    @RequestMapping("/product/select/top")
    public List<Product> selectTop(){
        List<Product> list = mapper.selectTop();
        for(Product p : list){
            String t = p.getTitle();
            if(t.length()>3){
                p.setTitle(t.substring(0,3)+"...");
            }
        }
        return list;
    }

    @RequestMapping("/product/select/category")
    public List<Product> selectByCid(int cid){
        return mapper.selectByCid(cid);
    }

    @RequestMapping("/search")
    public List<Product> search(String wd){
        return mapper.search(wd);
    }

    @RequestMapping("/product/selectById")
    public Product selectByIdProduct(int id){
        //每点击进入一次   浏览量加一
        mapper.updateViewCount(id);
        return mapper.selectByIdProduct(id);
    }

}
